$(function () {
  const apiBaseUrl = 'https://gate.97kid.com'
  const cdnBaseUrl = 'https://gstatic.97kid.com'
  const [lessonId, lessonType, lessonHash, noCache] = /\/wx\/books\/lessons\/([0-9]+)\/(sb|wb)\/?([0-9]+)?(\?noCache=1)?/g.exec(location.href).slice(1)

  document.title = lessonType === 'sb' ? '久趣课堂讲义' : '久趣练习册'

  $.ajax({
    type: 'GET',
    url: `${apiBaseUrl}/courses/lessons/${lessonId}/${lessonType + (noCache || '')}`,
    dataType: 'json',
    success: ({name, courseName, logoHDUri, questions}) => {
      $('.header .main').text(`Lesson ${name}`)
      $('.header .subhead').text(courseName)
      $('.header .banner').attr('src', cdnBaseUrl + logoHDUri)

      $.each(questions, (index, {id, questionNumber, title, description, sound}) => {
        $('.audio-list').append(`<div id="${id}" class="audio-card">
        <div class="audio-info">
          <div class="audio-id">${questionNumber}</div>
          <div class="audio-name">
            <div class="audio-name-en">${title}</div>
            <div class="audio-name-cn">${description}</div>
          </div>
        </div>
        <div class="audio-player">
          <audio id="audio-${id}" src="${cdnBaseUrl + sound}" preload></audio>
          <div id="audio-btn-${id}" class="play-btn play"></div>
          <div id="progress-${id}" class="progress-bar">
            <div id="progress-current-${id}" class="progress-bar-current"></div>
            <div id="progress-select-${id}" class="progress-bar-select"></div>
          </div>
          <div id="audio-time-${id}" class="audio-time">--:--</div>
        </div>
      </div>`)
        new AudioPlayer({
          audio: {
            el: `#audio-${id}`,
            playBtn: `#audio-btn-${id}`,
            time: `#audio-time-${id}`
          },
          progress: {
            el: `#progress-${id}`,
            current: `#progress-current-${id}`,
            select: `#progress-select-${id}`
          }
        })
      })

      if (lessonHash) setTimeout(() => window.scrollTo(0, $(`#${lessonHash}`).offset().top), 100)
    }
  })
})